
import { combineReducers } from 'redux';
import * as actionTypes from '../actionTypes';

// 初始化状态
const initialState = {
  checkoutStatus:{
    checkoutPending: false,
    message: null,
  },
  quantityById: {}
}

// 收到发起结算的action
function checkoutStatus(state = initialState.checkoutStatus, action) {
  switch (action.type) {
    case actionTypes.CHECKOUT_REQUEST:
      return {
        checkoutPending: true,
        message: "结算中..."
      }
    case actionTypes.CHECKOUT_SUCCESS:
      return {
        ...initialState,
        message: '结算成功'
      }
    case actionTypes.CHECKOUT_FAILURE:
      return {
        ...initialState,
        message: action.message
      }    
    default:
      return state
  }
}

// 获取购物车相关的操作
//  加入购物车的 只是一个产品Id, 具体显示的数据，会从product上面查询
function quantityById(state = initialState.quantityById, action) {
  const { productId } = action;
  switch (action.type) {
    // 加入购物车
    case actionTypes.ADD_TO_CART:
      return {
        ...state,
        [productId]: (state[productId] || 0) + 1
      }
    // 移除购物车  
    case actionTypes.REMOVE_FROM_CART:
     const qty = (state[productId] || 0) - 1;
     const copy = { ...state };
     if (qty > 0) copy[productId] = qty
     else delete copy[productId]
      return copy
    // 当结算成功时，清除购物车  
    case actionTypes.CHECKOUT_SUCCESS:
      return initialState.quantityById
    default:
      return state
  }
}

// 获取购物车里产品的数量
export function getQuantity(state, productId) {
  return state.quantityById[productId] || 0;
}

// 获取购物车里的id
export function getAddedIds(state) {
  return Object.keys(state.quantityById)
}

// 合并导出
export default combineReducers({
  quantityById,
  checkoutStatus
})
